<?php

namespace Beerus\Modules\DecoCompany\Actions;

use Doraemon\cache\Queue;
use Doraemon\cache\User as CacheUser;
use Doraemon\model\DecoCompany;
use Doraemon\model\DecoCompany\DecoCompanyAuditLog;
use Doraemon\model\DecoCompanyAuth;
use Doraemon\model\Member;
use Doraemon\service\es\EsDecoCompany;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class CancelAuth extends RowAction
{
	public $name = '取消认证';
	const TOAST_ALERT = '确定取消认证吗？';

	public function handle($id, Request $request)
	{
		$params = $request->all();
		$info = DecoCompany::get('*', [
			'id' => $id
		]);
		$uid = $info['uid'];
		Member::updateUserInfo($uid, [
			'type' => Member::USER_COMMON
		]);
		CacheUser::deleteUserInfo($uid);
		EsDecoCompany::delete($uid);
		Queue::insertQueue('User/addSearch', [
			'uid' => $uid,
			'type' => Member::USER_COMMON
		]);

		$res = DecoCompanyAuth::update([
			'auth_status' => DecoCompanyAuth::AUTH_STATUS_CANCEL,
			'admin_operate_time' => time(),
			'auth_expire_time' => time(),
			'admin_id' => Admin::user()->id,
			'admin_name' => Admin::user()->username
		], [
			'uid' => $uid
		]);
		DecoCompany::update([
			'auth_status' => DecoCompany::AUTH_STATUS_CANCEL,
			'is_show' => DecoCompany::SHOW_FALSE
		], [
			'id' => $id
		]);

		if ($res) {
			DecoCompanyAuditLog::insert([
				'uid' => $uid,
				'op_log' => json_encode([
					'op' => DecoCompanyAuditLog::OP_CANCEL_AUTH,
					'reason' => $params['reason']
				]),
				'admin_id' => Admin::user()->id,
				'admin_name' => Admin::user()->username
			]);
			return $this->response()->success('操作成功(＾－＾)V')->refresh();
		}else{
			return $this->response()->success('操作失败,请稍后重试o(TωT)o');
		}
	}

	public function retrieveModel(Request $request)
	{
		if (!$key = $request->get('_key')) {
			return false;
		}
		return $key;
	}

	public function form()
	{
		$this->textarea('reason', '取消认证的原因')->required('不能为空');

		$this->confirm(self::TOAST_ALERT);
	}
}
